// pages/mine/mine.js
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    nickName:"",//用户名
    avatarUrl:"",//用户头像
    phone:"",//用户手机号码
    hadAuthd:false//登录凭证
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //当用户登录过时,获取用户头像昵称 隐藏一键注册
    if(wx.getStorageSync('hadAuthd')){
      var userInfo = wx.getStorageSync('userInfo');
        this.setData({
          nickName: userInfo.nickName,
          avatarUrl: userInfo.avatarUrl,
          hadAuthd:true
        })
      this.getKeyInfo();//获取用户手机号码
    } 
  },
  //跳转到优惠券
  // gocut:function(){
  //   wx.navigateTo({
  //     url: '../cut/cut'
  //   })
  // },
  //联系客服电话
  bitphone:function(){
     // 拨打手机号码
    wx.makePhoneCall({
      phoneNumber: '4001118024' //需要拨打的号码
    })
  },
  //绑定手机号码 - 以获取优惠券
  getPhoneNumber: function (e) {
    var that = this;
      wx.request({
        url: app.globalData.apiHost +'/ ?openId=' + wx.getStorageSync('openId'), //注册
        method: 'POST',
        data: {
          "encryptedData": e.detail.encryptedData,
          "iv": e.detail.iv,
          "session": wx.getStorageSync('session_key'),
        },
        dataType: 'json',
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          that.getKeyInfo()//获取用户手机号码
        }
      })
  } ,

  //用户未登录注册没有头像昵称- 指引去登录注册
  getUserInfo: function (e) {
    //获取用户信息
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        var userInfo = res.userInfo
        //将用户信息连同 app.js获得的openid(用于注册)一同存入本地
        userInfo.openId = wx.getStorageSync('openId');
        wx.setStorageSync('userInfo', userInfo);
        console.log(userInfo)
        //开始注册用户
        wx.request({
          url: app.globalData.apiHost +'/register', //注册
          method: 'POST',
          data: userInfo,
          dataType: 'json',
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            console.log(res.data)
          }
        })
        //登陆过的凭证
        wx.setStorageSync('hadAuthd', true);
        this.setData({
          nickName: userInfo.nickName,
          avatarUrl: userInfo.avatarUrl,
          hadAuthd:true
        })
      }
    })
  },
  //获取用户手机号码
  getKeyInfo:function(){
    var that =this;
    wx.request({
      url: app.globalData.apiHost +'/getMyInfo?openId=' + wx.getStorageSync('openId'), //获取用户信息
      success: function (res) {
        console.log(res.data.data)
        that.setData({
          phone: res.data.data[0].phone,
        })
      }
    })
  }
})